package com.xyj.zjbz.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;

import com.xyj.zjbz.po.ZJDataSource;
import com.xyj.zjbz.vo.MysqlUrl;

/**
 * mysql备份工具（只适用于windows环境，基于cmd命令，必需先配置好mysql环境变量）
 * 
 * @author 李朝衡
 * 
 */
public class MySqlUtil {

	private static final Logger log = Logger.getLogger(MySqlUtil.class
			.getName());

	/**
	 * 数据库备份
	 * 
	 * @param m
	 * @param path
	 * @throws IOException
	 */
	public static void backupDb(MysqlUrl m, String path) throws IOException {
		Runtime runtime = Runtime.getRuntime();
		String command = "cmd.exe /c mysqldump -u" + m.getUserName() + " -p"
				+ m.getPwd() + " -h" + m.getIp() + " -P" + m.getPort() + " "
				+ m.getDbName() + " >" + path;
		log.info("command:" + command);
		runtime.exec(command);
		log.info("数据库[" + m.getDbName() + "]备份完成 !=======" + "备份路径：" + path);
	}

	/**
	 * 创建一个datasource
	 */
	public static void createDataSource(ZJDataSource bz, MysqlUrl mysqlAdmin) {
		String s = MySqlUtil.class.getClassLoader().getResource("dynamic")
				.getPath().replaceFirst("/", "");
		String templPath = "dynamic/cmd.txt";//cmd命令
		InputStream in = MySqlUtil.class.getClassLoader().getResourceAsStream(
				templPath);
		InputStreamReader reader = null;
		Runtime run = Runtime.getRuntime();
		try {
			reader = new InputStreamReader(in, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(reader);
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				String cmd = line
						.replace("$adminUser", mysqlAdmin.getUserName())
						.replace("$adminPwd", mysqlAdmin.getPwd())
						.replace("$ip", mysqlAdmin.getIp())
						.replace("$port", mysqlAdmin.getPort())
						.replace("$newUser", bz.getDbUserName())
						.replace("$userPwd", bz.getDbPwd())
						.replace("$dbName", bz.getBzDB())
						.replace("$sqlPath", s + "/table.sql");
				//一行一行的执行cmd命令
				run.exec("cmd /c " + cmd);
			}
			bufferedReader.close();
			reader.close();
			in.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
